#include <string.h>
#include "DictionaryTree.h"

using namespace std;

DictionaryNode * DictionaryTree::GiveLetter(DictionaryNode * parse, char letter)
{
	if (letter < 'A' || letter > 'Z')
	{
		return 0;
	}

	int index = letter - 'A';

	return parse->Letters[index];	
}

void DictionaryTree::AddWord(char * word)
{
	int i;
	DictionaryNode * curr = &head;

	//size_t length = strlen(word);

	for (i=0;i<15;i++)
	{
		if (!word[i] || word[i] < 'A' || word[i] > 'Z')
		{
			curr->isword = true;
			return;
		}

		int index = word[i] - 'A';

		if (1) //length <= 6)
		{
			letcount[index]++;
			numletters++;
		}

		if (numletters < 0) printf("Integer overflow!!");
		
		if (!curr->Letters[index])
		{
			curr->Letters[index] = new DictionaryNode();
		}
		curr = curr->Letters[index];
	}
}

DictionaryTree::DictionaryTree(const char * dictionaryfile)
{
	ifstream dict;

	dict.open(dictionaryfile);

	if (!dict) {
		printf("Unable to open dictionary: %s\n", dictionaryfile);
    }

	numletters = 0;
	for (int l=0;l<26;l++)
	{
		letprob[l] = 0;
		letcount[l] = 0;
	}

	char Word[32];

	printf("Parsing Dictionary\n");

	while (dict.getline(Word, 31))
	{
		//printf("Unable to open dictionary: %s\n", Word);
		if (strchr(Word, '%')) continue; 

		AddWord(Word);
	}

	printf("Dictionary parsed\n");

    dict.close();

	for (int l=0;l<26;l++)
	{
		letprob[l] = (double)letcount[l] / (double)numletters;
	}
}

DictionaryTree::~DictionaryTree(void)
{
	
}
